<?php

namespace Package\RedisHelper;

use Package\RedisHelper\Connection\ConnectionManager;
use Package\RedisHelper\Connection\RedisConnection;
use Package\RedisHelper\Exceptions\RedisOperationException;

class RedisHelper
{
    protected $redis;
    protected $connection;
    
    public function __construct($config, string $connectionName = 'default')
    {
        $this->connection = ConnectionManager::getConnection($config, $connectionName);
        $this->redis = $this->connection->getRedis();
    }
    
    // 所有操作方法保持不变，但增加重连机制
    public function set(string $key, $value, int $ttl = 0): bool
    {
        try {
            if ($ttl > 0) {
                return $this->redis->setex($key, $ttl, $value);
            }
            return $this->redis->set($key, $value);
        } catch (\RedisException $e) {
            // 尝试重连一次
            try {
                $this->connection->reconnect();
                return $this->set($key, $value, $ttl);
            } catch (\Exception $retryEx) {
                throw new RedisOperationException("Redis set operation failed: " . $e->getMessage(), 0, $e);
            }
        }
    }
    
    // 其他方法同样添加重试机制...
    
    /**
     * 获取底层连接对象
     */
    public function getConnection(): RedisConnection
    {
        return $this->connection;
    }
}